package terra.network.packet;

import java.io.UnsupportedEncodingException;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;

public abstract class Packet{

	public static final byte PRIOR_LOW =0;
	public static final byte PRIOR_NORMAL =1;
	public static final byte PRIOR_HIGH =2;
	
	public abstract ChannelBuffer toBuffer();
	public abstract Packet fromBuffer(ChannelBuffer buf);
	public abstract int getLength();
	public abstract boolean isDynamicLength();
	public abstract byte getId();
	public abstract byte getPriority();
	
	protected ChannelBuffer getNewBuffer(int length){
//		return ChannelBuffers.directBuffer(length);
		return ChannelBuffers.buffer(length);
	}
	
	protected ChannelBuffer getNewBuffer(){
		return ChannelBuffers.directBuffer(getLength());
//		return ChannelBuffers.buffer(getLength());
	}
	
	protected byte[] stringToBytes(String s) {
		try {
			return s.getBytes("UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	protected String bytesToString(byte[] bytes) {
		try {
			return new String(bytes, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public void delete(){
		try {
			finalize();
		} catch (Throwable e) {
			e.printStackTrace();
		}
	}

}
